﻿using Batman.Cms.Core;
using Batman.Cms.Loaders;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Cms.Hosting
{
    public static class PluginStartup
    {

        public static List<Type> PluginStartupTypes = new List<Type>();

        public static List<IPluginStartup> PluginStartups;

        /// <summary>
        /// 反射出插件中的Startup配置文件
        /// </summary>
        public static void ConfigureServices(this IServiceCollection services, IHostingEnvironment env)
        {
            var plugins = env.GetPlugins();

            foreach (var plugin in plugins)
            {
                foreach (var typeInfo in plugin.Assembly.DefinedTypes)
                {
                    if (typeInfo.ImplementedInterfaces.Any(t => t == (typeof(IPluginStartup))))
                    {

                        services.AddTransient(typeInfo.AsType());
                        PluginStartupTypes.Add(typeInfo.AsType());

                    }else 
                    {
                        services.AddTransient(typeInfo.AsType());
                    }
                }
            }

            var provider = services.BuildServiceProvider();

            PluginStartups = PluginStartupTypes.Select(t => provider.GetService(t) as IPluginStartup).ToList();

            PluginStartups.ForEach(t => t.ConfigureServices(services));
        }

        public static void Configure(this IApplicationBuilder app, IHostingEnvironment env)
        {
            PluginStartups.ForEach(t => t.Configure(app, env));
        }
    }
}
